<?php

namespace App\Service\Kms\Task;

use App\Enums\OpenShop\InvestmentPromotion\OrganizationManageEnum;
use App\Error\Kms\KmsTaskError;
use App\Events\Kms\DailyTaskCreateEvent;
use App\Exceptions\KfHttpResponseException;
use App\Models\Common\AmapAreaModel;
use App\Models\Kms\Task\DailyTaskLogsModel;
use App\Models\Kms\Task\TaskModel;
use App\Models\Kms\Task\TaskNodesModel;
use App\Models\Kms\Task\TaskNodesProcessorModel;
use App\Models\Kms\Task\TaskTemplateModel;
use App\Models\Kms\Task\TaskTemplateNodesModel;
use App\Models\Kms\Task\TaskTemplateNodesProcessorModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Remote\Rms\RmsShopRemote;
use App\Service\BaseService;
use App\Service\Kms\Shop\ShopService;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class TaskService extends BaseService
{
    /**
     * @param array $userRole
     * @return array
     */
    private static function buildUserRoleArea(array $userRole): array
    {
        $authProvinceCodes = [];
        $remoteRequestArea = ["province" => [], "city" => [], "district" => []];

        $roleProvince = attributeGet($userRole, "userResponsibleArea.fullArea.province", []);

        $authProvinceCodes             = array_merge($authProvinceCodes, $roleProvince);
        $remoteRequestArea["province"] = array_merge($remoteRequestArea["province"], $roleProvince);

        $roleCity = attributeGet($userRole, "userResponsibleArea.fullArea.city", []);

        collect($roleCity)->each(function ($city) use (&$authProvinceCodes, &$remoteRequestArea) {
            $authProvinceCodes         = array_merge($authProvinceCodes, [$city[0]]);
            $remoteRequestArea["city"] = array_merge(
                $remoteRequestArea["city"],
                [["province" => $city[0], "city" => $city[1]]]
            );
        });

        $roleDistrict = attributeGet($userRole, "userResponsibleArea.fullArea.district", []);

        collect($roleDistrict)->each(function ($district) use (&$authProvinceCodes, &$remoteRequestArea) {
            $authProvinceCodes             = array_merge($authProvinceCodes, [$district[0]]);
            $remoteRequestArea["district"] = array_merge(
                $remoteRequestArea["district"],
                [["province" => $district[0], "city" => $district[1], "district" => $district[2]]]
            );
        });

        return compact("authProvinceCodes", "remoteRequestArea");
    }

    /**
     * 预请求门店列表
     *
     * @return array|void
     * @throws Exception
     */
    public static function preShopList()
    {
        try {
            $userRole                = UserRoleService::getUserRole(auth()->user()->rmsUserId);
            $authProvinceCodes       = [];
            $province                = collect();
            $authRemoteProvinceCodes = $authRemoteCityCodes = $authRemoteDistrictCodes = [];
            if (!$userRole["userResponsibleArea"]["all"]) {
                switch ($userRole["role"]) {
                    case UserRoleService::ROLE_BASE_SUPERVISOR:
                        break;
                    case UserRoleService::ROLE_BASE_CITY_MANAGER:
                    case UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER:
                    case UserRoleService::ROLE_BASE_PROVINCE:
                    case UserRoleService::ROLE_BASE_WAR_REGION:
                        $userRoleArea            = self::buildUserRoleArea($userRole);
                        $authProvinceCodes       = $userRoleArea["authProvinceCodes"];
                        $remoteRequestArea       = $userRoleArea["remoteRequestArea"];
                        $authRemoteProvinceCodes = $remoteRequestArea["province"];
                        $authRemoteCityCodes     = collect($remoteRequestArea["city"])
                            ->pluck("city")
                            ->toArray();
                        $authRemoteDistrictCodes = collect($remoteRequestArea["district"])
                            ->pluck("district")
                            ->toArray();
                        break;
                    default:
                        throw new KfHttpResponseException(KmsTaskError::USER_ROLE_CAN_NOT_CREATE_DAILY_TASK);
                        break;
                }

                $authProvinceCodes = array_values(array_unique($authProvinceCodes));
                if (!empty($authProvinceCodes)) {
                    $province = AmapAreaModel::query()
                                             ->whereIn("code", $authProvinceCodes)
                                             ->where("level", AmapAreaModel::LEVEL_PROVINCE)
                                             ->select(["label", "code", "pCode", "level"])
                                             ->orderBy("label")
                                             ->get();
                }
            } else {
                $province                = AmapAreaModel::query()
                                                        ->where("level", AmapAreaModel::LEVEL_PROVINCE)
                                                        ->select(["label", "code", "pCode", "level"])
                                                        ->orderBy("label")
                                                        ->get();
                $authRemoteProvinceCodes = $province->pluck("code")->toArray();
            }

            $shopList = collect(RmsShopRemote::getShopListByArea(
                1,
                $authRemoteProvinceCodes,
                $authRemoteCityCodes,
                $authRemoteDistrictCodes
            )["list"]);

            return [
                "role"                => $userRole["role"],
                "userResponsibleArea" => $userRole["userResponsibleArea"],
                "roleDesc"            => $userRole["desc"],
                "provinceInfo"        => [
                    "count" => count($province),
                    "list"  => $province->map(function ($row) use ($shopList) {
                        $row->shopCount = attributeGet($shopList->where("province", $row->code)->first(), "total", 0);
                        return $row;
                    })->values()->toArray()
                ]
            ];

        } catch (\Exception $exception) {
            handleKfException($exception);
        }
    }

    /**
     * @param object $params
     * @return array|void
     * @throws GuzzleException
     */
    public static function shopListV2(object $params)
    {
        try {
            $userRole = UserRoleService::getUserRole(auth()->user()->rmsUserId);
            if (!in_array($userRole["role"], [
                UserRoleService::ROLE_BASE_CITY_MANAGER,
                UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,
                UserRoleService::ROLE_BASE_PROVINCE,
                UserRoleService::ROLE_BASE_SUPERVISOR,
                UserRoleService::ROLE_BASE_WAR_REGION,
            ])) {
                throw new KfHttpResponseException(KmsTaskError::USER_ROLE_HAS_NO_ACCESS_AUTHORITY);
            }
            switch ($params->role) {
                case UserRoleService::ROLE_BASE_SUPERVISOR:
                    $signOrder = OpenShopSignOrderModel::query()->whereHas("checkAcceptRel", function ($query) {
                        $query->where("managerId", auth()->user()->rmsUserId);
                    })->get();
                    if ($signOrder->isNotEmpty()) {
                        $shopList = RmsShopRemote::getShopFieldsByCodes(
                            $signOrder->pluck("shopCode")->toArray(),
                            [
                                "id",
                                "shopCode",
                                "name",
                                "province",
                                "city",
                                "district",
                                "address",
                                "addressPrefix"
                            ]
                        );
                        $total    = count($shopList["shopList"]);
                        $list     = $shopList["shopList"];
                    } else {
                        $total = 0;
                        $list  = [];
                    }
                    break;
                default:
                    $userRoleArea      = self::buildUserRoleArea($userRole);
                    $authProvinceCodes = $userRoleArea["authProvinceCodes"];
                    if (!$userRole["userResponsibleArea"]["all"] && !in_array($params->province, $authProvinceCodes)) {
                        throw new KfHttpResponseException(KmsTaskError::USER_HAS_NO_AUTH_ACCESS_PROVINCE);
                    }
                    $remoteRequestArea = $userRoleArea["remoteRequestArea"];
                    $province          = in_array(
                        $params->province,
                        $remoteRequestArea["province"]
                    ) ? [$params->province] : [];

                    $city = collect($remoteRequestArea["city"])
                        ->where("province", $params->province)
                        ->pluck("city")
                        ->toArray();

                    $district = collect($remoteRequestArea["district"])
                        ->where("province", $params->province)
                        ->pluck("district")
                        ->toArray();

                    $shopList = RmsShopRemote::getShopListByArea(0, $province, $city, $district);
                    $total    = $shopList["total"];
                    $list     = $shopList["list"];
                    break;
            }

            return [
                "total" => $total,
                "list"  => $list
            ];
        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }


    /**
     * 日常任务门店下拉列表
     *
     * @param object $params
     * @return array
     * @throws Exception|GuzzleException
     */
    public static function shopList(object $params): array
    {
        try {
            $shopList = [];
            list($role, $roleDesc, $isAttachProvince, $provinceCodes, $cityCodes, $areaCodes) = UserRoleService::getUserRole(auth()->user()->rmsUserId);
            switch ($role) {
                case UserRoleService::ROLE_BASE_SUPERVISOR:
                    $signOrder = OpenShopSignOrderModel::query()->whereHas("checkAcceptRel", function ($query) {
                        $query->where("managerId", auth()->user()->rmsUserId);
                    })->get();
                    if ($signOrder->isNotEmpty()) {
                        $shopList = ShopService::shopList($role, [], [], [], $params->keywords,
                            $signOrder->pluck("shopCode")->toArray());
                    }
                    break;
                default:
                    $shopList = ShopService::shopList($role, $provinceCodes, $cityCodes, $areaCodes, $params->keywords);
                    break;
            }
            return [
                "count" => $shopList["total"] ?? 0,
                "list"  => $shopList["list"] ?? []
            ];
        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }

    /**
     * 督导列表
     *
     * @param object $params
     * @return array|void
     * @throws Exception
     */
    public static function supervisorList(object $params)
    {
        try {
            $userRole  = UserRoleService::getUserRole(auth()->user()->rmsUserId);
            $canSelect = true;
            if ($userRole["role"] == UserRoleService::ROLE_BASE_SUPERVISOR || count($params->shopInfo) > 1) {
                $canSelect = false;
            }

            $getUserAvatarFunc = function (array $managerInfo) {
                $userIds = collect($managerInfo)->map(function (array $manager) {
                    return attributeGet($manager, "manager.managerId", 0);
                })->values()->toArray();


                $kmsUserInfo = KmsUser::query()->whereIn("rmsUserId", $userIds)->get();
                return collect($managerInfo)->map(function (array $manager) use ($kmsUserInfo) {
                    $manager["manager"]["avatar"] = attributeGet(
                        $kmsUserInfo->where("rmsUserId", attributeGet($manager, "manager.managerId", 0))->first(),
                        "avatar",
                        ""
                    );
                    return $manager;
                })->values()->toArray();
            };

            $shopOrderRel = OpenShopSignOrderModel::query()
                                                  ->whereIn("shopCode",
                                                      collect($params->shopInfo)->pluck("shopCode")->toArray())
                                                  ->with("checkAcceptRel")
                                                  ->get();

            if ($shopOrderRel->count() != count($params->shopInfo)) {
                $errShopCodes = collect(array_diff(
                    collect($params->shopInfo)->pluck("shopCode")->toArray(),
                    $shopOrderRel->pluck("shopCode")->toArray()
                ))->implode(",");
                throw new KfHttpResponseException(KmsTaskError::SHOP_SEARCH_OPEN_SHOP_ORDER_FAIL);
            }

            $originalManagerSelection = $shopOrderRel->map(function (OpenShopSignOrderModel $signOrderModel) {
                if (empty($signOrderModel->checkAcceptRel) || empty($signOrderModel->checkAcceptRel->managerId)) {
                    throw new KfHttpResponseException(KmsTaskError::SHOP_HAS_NO_SUPERVISOR);
                }
                return [
                    "shopCode" => $signOrderModel->shopCode,
                    "manager"  => [
                        "managerName" => $signOrderModel->checkAcceptRel->managerName,
                        "managerId"   => $signOrderModel->checkAcceptRel->managerId
                    ],
                    "selected" => 1
                ];
            })->values()->toArray();

            $role = UserRoleService::getUserRole(auth()->user()->rmsUserId)["role"];
            if (count($params->shopInfo) > 1 || $role == UserRoleService::ROLE_BASE_SUPERVISOR) {
                //(选中超过一家门店 || 用户角色为督导) 直接返回督导信息
                return [
                    "selection" => $getUserAvatarFunc($originalManagerSelection),
                    "canSelect" => $canSelect
                ];
            }

            //选中一家门店业务处理
            $shopInfo       = current($params->shopInfo);
            $shopManager    = current($originalManagerSelection);
            $provinceConfig = OpenShopOrganizationManageModel::query()
                                                             ->where("type", OrganizationManageEnum::TYPE_BRANCH_OFFICE)
                                                             ->whereHas("regionRel",
                                                                 function ($query) use ($shopInfo) {
                                                                     $query->where("provinceCode",
                                                                         $shopInfo["province"]);
                                                                 })
                                                             ->with([
                                                                 "managerUserRel" => function ($query) {
                                                                     $query->where("type",
                                                                         OpenShopOrganizationManageUserModel::TYPE_INCREASE_MANAGER);
                                                                 }
                                                             ])->first();

            if (empty($provinceConfig)) {
                //获取开店配置失败 直接返回
                return [
                    "selection" => $getUserAvatarFunc($originalManagerSelection),
                    "canSelect" => $canSelect
                ];
            } else {
                //开店配置督导信息 + 门店已分配督导
                $provinceConfigManager = $provinceConfig->managerUserRel
                    ->map(function (OpenShopOrganizationManageUserModel $manageUserModel) use (
                        $shopInfo,
                        $shopManager
                    ) {
                        return [
                            "shopCode" => $shopInfo["shopCode"],
                            "manager"  => [
                                "managerName" => $manageUserModel->name,
                                "managerId"   => $manageUserModel->userId
                            ],
                            "selected" => $manageUserModel->userId == $shopManager["manager"]["managerId"] ? 1 : 0
                        ];
                    })->values();

                if ($provinceConfigManager->where("selected", 1)->count() == 0) {
                    $provinceConfigManager->push($shopManager);
                }
                return [
                    "selection" => $getUserAvatarFunc($provinceConfigManager->toArray()),
                    "canSelect" => $canSelect
                ];
            }

        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }

    /**
     * 日常任务创建
     *
     * @param object $params
     * @param int $uid
     * @param int $templateType
     * @throws Exception
     */
    public static function add(object $params, int $uid, int $templateType = TaskTemplateModel::TEMPLATE_TYPE_0)
    {
        try {
            $params->time         = time();
            $params->templateType = $templateType;
            $sign                 = md5(json_encode((array)$params, JSON_UNESCAPED_UNICODE));

            $addFunction = "handleAddTemplate_{$templateType}";
            $insertData  = self::{$addFunction}($params, $sign, $uid);


            DailyTaskLogsModel::query()->insert($insertData);
            event(new DailyTaskCreateEvent($sign));
        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }

    /**
     * kms - 每日日常任务
     *
     * @param object $params
     * @param string $sign
     * @param int $uid
     * @return array
     * @throws ValidationException
     */
    public static function handleAddTemplate_0(object $params, string $sign, int $uid): array
    {
        $role = UserRoleService::getUserRole($uid)["role"];
        if (!in_array($role, [
            UserRoleService::ROLE_BASE_CITY_MANAGER,
            UserRoleService::ROLE_BASE_DEVELOP_CITY_MANAGER,
            UserRoleService::ROLE_BASE_PROVINCE,
            UserRoleService::ROLE_BASE_SUPERVISOR
        ])) {
            throw new KfHttpResponseException(KmsTaskError::USER_ROLE_CAN_NOT_CREATE_DAILY_TASK);
        }

        $allOrganizationManage = OpenShopOrganizationManageModel::allOrganizationManage(0);
        return collect($params->shopMap)->map(function ($shop) use (
            $sign,
            $params,
            $role,
            $allOrganizationManage,
            $uid
        ) {
            switch ($role) {
                case UserRoleService::ROLE_BASE_SUPERVISOR:
                    //找出门店所属区域的城市经理和省总信息
                    $approveUserIds = [];
                    $allOrganizationManage->each(function (OpenShopOrganizationManageModel $organizationManageModel
                    ) use ($shop, &$approveUserIds, $uid) {
                        $isProvince = $organizationManageModel->regionRel->where("provinceCode",
                            $shop["province"])->first();
                        if ($isProvince) {
                            array_push($approveUserIds, $organizationManageModel->operationUid);
                            $cityManager = null;
                            $organizationManageModel->managerUserRel
                                ->where("type", OpenShopOrganizationManageUserModel::TYPE_CITY_MANAGER)
                                ->each(function (OpenShopOrganizationManageUserModel $manageUserModel
                                ) use (&$cityManager, $shop) {
                                    if (is_null($cityManager) && str_contains($manageUserModel->addressCodes,
                                            $shop["city"])) {
                                        $cityManager = $manageUserModel->userId;
                                    }
                                });
                            if ($cityManager) {
                                array_push($approveUserIds, $cityManager);
                            }
                        }
                        if (!empty($approveUserIds)) {
                            return false;
                        }
                    });

                    break;
                default:
                    $approveUserIds = [$uid];
                    break;
            }

            return array_merge(
                [
                    "templateType"   => $params->templateType,
                    "shopId"         => $shop["id"],
                    "taskType"       => $params->taskType,
                    "handlerUserId"  => $shop["handleUserId"],
                    "approveUserIds" => json_encode($approveUserIds, JSON_UNESCAPED_UNICODE),
                    "uniqueSign"     => $sign,
                    "desc"           => $params->desc,
                    "createdAt"      => $params->time,
                    "createdByUid"   => $uid
                ],
                empty($params->descImg) ? [] : [
                    "descImg" => json_encode($params->descImg, JSON_UNESCAPED_UNICODE)
                ]
            );
        })->values()->toArray();
    }

    /**
     * 客服 - 每日日常任务
     *
     * @param object $params
     * @param string $sign
     * @param int $uid
     * @return array
     */
    public static function handleAddTemplate_1(object $params, string $sign, int $uid): array
    {

        $allOrganizationManage = OpenShopOrganizationManageModel::allOrganizationManage(0);
        return collect($params->shopMap)->map(function ($shop) use (
            $sign,
            $params,
            $allOrganizationManage,
            $uid
        ) {
            //找出门店所属区域的城市经理和省总信息
            $approveUserIds = [];
            $allOrganizationManage->each(function (OpenShopOrganizationManageModel $organizationManageModel
            ) use ($shop, &$approveUserIds, $uid) {
                $isProvince = $organizationManageModel->regionRel->where("provinceCode",
                    $shop["province"])->first();
                if ($isProvince) {
                    array_push($approveUserIds, $organizationManageModel->operationUid);
                    $cityManager = null;
                    $organizationManageModel->managerUserRel
                        ->where("type", OpenShopOrganizationManageUserModel::TYPE_CITY_MANAGER)
                        ->each(function (OpenShopOrganizationManageUserModel $manageUserModel
                        ) use (&$cityManager, $shop) {
                            if (is_null($cityManager) && str_contains($manageUserModel->addressCodes,
                                    $shop["city"])) {
                                $cityManager = $manageUserModel->userId;
                            }
                        });
                    if ($cityManager) {
                        array_push($approveUserIds, $cityManager);
                    }
                }
                if (!empty($approveUserIds)) {
                    return false;
                }
            });

            return array_merge(
                [
                    "templateType"   => $params->templateType,
                    "shopId"         => $shop["id"],
                    "taskType"       => $params->taskType,
                    "handlerUserId"  => $shop["handleUserId"],
                    "approveUserIds" => json_encode($approveUserIds, JSON_UNESCAPED_UNICODE),
                    "uniqueSign"     => $sign,
                    "desc"           => $params->desc,
                    "createdAt"      => $params->time,
                    "createdByUid"   => $uid
                ],
                empty($params->descImg) ? [] : [
                    "descImg" => json_encode($params->descImg, JSON_UNESCAPED_UNICODE)
                ]
            );
        })->values()->toArray();
    }

    /**
     * 任务详情
     *
     * @param object $params
     * @return array|void
     * @throws GuzzleException
     */
    public static function detail(object $params)
    {
        try {
            $dailyTaskModel = DailyTaskLogsModel::query()
                                                ->with([
                                                    "taskRel" => function ($query) {
                                                        $query->with([
                                                            "taskNodesRel" => function ($query) {
                                                                $query->with("nodesProcessorRel")->orderBy("id", "asc");
                                                            }
                                                        ]);
                                                    }
                                                ])
                                                ->where("id", $params->id)
                                                ->first();


            $kmsUserModel = KmsUser::query()->whereIn("rmsUserId",
                [$dailyTaskModel->handlerUserId, $dailyTaskModel->createdByUid])->get();

            $mobile   = attributeGet($dailyTaskModel, "mainProcessRel.userBaseInfoRel.mobile", null);
            $birthday = attributeGet($dailyTaskModel, "mainProcessRel.identityCardRel.birthday", null);
            $username = attributeGet($dailyTaskModel, "mainProcessRel.identityCardRel.name", null);
            return array_merge([
                "hasPower"       => Common\TaskService::checkUserPower(
                    $dailyTaskModel->taskRel,
                    auth()->user()->rmsUserId
                ),
                "showInvalidBtn" => $dailyTaskModel->taskRel->status == TaskModel::TASK_STATUS_ING && $dailyTaskModel->taskRel->createdByUid == auth()->user()->rmsUserId,
                "userBaseInfo"   => [
                    "mobile"   => $mobile,
                    "username" => $username,
                    "age"      => $birthday ? date("Y", time()) - substr($birthday, 0, 4) : null
                ],
                "shopInfo"       => collect(RmsShopRemote::getShopDetailByShopId($dailyTaskModel->shopId)["shopDetail"])
                    ->only(["name", "shopCode", "address", "addressPrefix"]),
            ], [
                "taskDetail" => [
                    "handlerUserInfo" => $kmsUserModel->where("rmsUserId", $dailyTaskModel->handlerUserId)
                                                      ->first()->only(["name", "nickname", "rmsUserId"]),
                    "creatorInfo"     => $kmsUserModel->where("rmsUserId", $dailyTaskModel->createdByUid)
                                                      ->first()->only(["name", "nickname", "rmsUserId"]),
                    "createdAt"       => $dailyTaskModel->createdAt->format("Y-m-d H:i:s"),
                    "desc"            => $dailyTaskModel->desc,
                    "descImg"         => jsonToArr($dailyTaskModel->descImg, []),
                    "taskType"        => $dailyTaskModel->taskType,
                    "taskTypeText"    => DailyTaskLogsModel::TASK_TYPE_TEXT[$dailyTaskModel->taskType] ?? "",
                    "status"          => $dailyTaskModel->taskRel->status,
                    "statusText"      => TaskModel::TASK_STATUS_TEXT[$dailyTaskModel->taskRel->status] ?? "",
                ]
            ], [
                    "progress" => Common\TaskService::getTaskProgress($dailyTaskModel->taskRel)
                ]
            );

        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }

    /**
     * @param object $params
     * @throws Exception
     */
    public static function approval(object $params)
    {
        try {
            $dailyTaskModel = DailyTaskLogsModel::query()
                                                ->where("id", $params->id)
                                                ->first();

            Common\TaskService::operateValidate(
                $dailyTaskModel->taskRel,
                TaskTemplateNodesModel::BUSINESS_TYPE_APPROVE,
                auth()->user()->rmsUserId
            );

            (new Common\TaskService())->nextNode(
                $dailyTaskModel->taskRel,
                auth()->user()->rmsUserId,
                [],
                $params->approvalResult,
                attributeGet($params, "remark", "")
            );
        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }


    /**
     * 作废任务
     *
     * @param object $params
     * @throws Exception
     */
    public static function invalid(object $params)
    {
        try {
            $dailyTaskModel = DailyTaskLogsModel::query()
                                                ->where("id", $params->id)
                                                ->first();

            if ($dailyTaskModel->taskRel->createdByUid != auth()->user()->rmsUserId) {
                throw new KfHttpResponseException(KmsTaskError::HAVE_NO_PERMISSION_TO_OPERATE_THE_CURRENT_TASK_NODE);
            }

            //作废任务
            (new Common\TaskService())->invalid(
                $dailyTaskModel->taskRel,
                auth()->user()->rmsUserId,
                vsprintf(
                    "%s(%s)",
                    [
                        auth()->user()->name,
                        auth()->user()->nickname
                    ]
                )
            );
        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }

    /**
     * 任务表单提交
     *
     * @param object $params
     * @throws Exception
     */
    public static function submit(object $params)
    {
        try {
            $dailyTaskModel = DailyTaskLogsModel::query()
                                                ->where("id", $params->id)
                                                ->first();

            Common\TaskService::operateValidate(
                $dailyTaskModel->taskRel,
                TaskTemplateNodesModel::BUSINESS_TYPE_SUBMIT,
                auth()->user()->rmsUserId
            );

            (new Common\TaskService())->nextNode($dailyTaskModel->taskRel, auth()->user()->rmsUserId, $params->form);
        } catch (Exception $exception) {
            handleKfException($exception);
        }
    }
}
